import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { Component, OnInit, ViewChild, ElementRef, Input, Output, EventEmitter } from '@angular/core';

import { NavController, ModalController, LoadingController } from '@ionic/angular';
import { NavParams, Platform } from '@ionic/angular';

import { ChooseCityComponent } from '../../choose-city/choose-city.component';
import { AppGlobalService } from '../../../shared/service/app-global.service';
import { MapBaiduService } from '../../../shared/service/map.baiduapi';
// import AddressParse from 'address-parse';
import { HttpService } from 'src/app/shared/service/http.service';

declare var cordova: any;
declare var BMap;
declare var BMAP_ANCHOR_BOTTOM_RIGHT;
@Component({ selector: 'app-show-map', templateUrl: './show-map.page.html', styleUrls: ['./show-map.page.scss'] })
export class ShowMapPage implements OnInit {
  @ViewChild('addressMap') mapElement: ElementRef;
  public flag = true; // 如果为true显示地图 为false执行搜索
  private surroundingBusiness: any = {};
  private searchList: any = {};
  private map: any;
  private mapId: any;          // 地图元素的id
  public streetDetail: any;    // 获取指定经纬度的  街道street +门牌号streetNumber
  private clicked = false;    // 是否已经点击过地图
  private cityCode: any;
  public cityName: any;
  private myGeo = { lng: 113.931058, lat: 22.517712 };
  emptyDataHint = '暂未查询到相关信息';
  @Input() formData: any; // 来自表单参数
  @Input() value: any; // 来自弹窗参数
  @Output() updateAddress: EventEmitter<any> = new EventEmitter();
  @Input() tagData: any;// 来自页面的数据

  constructor(
    private navController: NavController,
    // public navParams: NavParams,
    public modalController: ModalController,
    private mapBaiduService: MapBaiduService,
    private appGlobalService: AppGlobalService,
    private loadingCtrl: LoadingController,
    private pageModalService: PageModalService,
    private http: HttpService,
    private platform: Platform) {

  }
  data: any;
  ac: any;
  appTypeCustom: any;
  areaPositionInfo: any;
  positionInfo: any;
  mapSearchType: any;


  communityKey = "小区";
  radius = 1000;// 搜索半径 单位/米
  headerTitle = "选择地址"; // 标题栏名字
  cityNameCssStyle = 'display:none;';
  downArrowIconCssStyle = 'display:none;'
  async ngOnInit() {

    if (this.tagData !== undefined && this.formData === undefined && this.value === undefined) {
      if (this.tagData.data.headerTitle) {
        this.headerTitle = this.tagData.data.headerTitle;
      }

      if (this.tagData.data.mapSearchType !== undefined) {
        this.mapSearchType = this.tagData.data.mapSearchType;
      }
      const currentTarget = this.appGlobalService.getCurrentTarget();
      console.log('currentTarget', currentTarget);
      if (currentTarget.params
        && currentTarget.params.showMapPage
        && currentTarget.params.showMapPage === 'true'
        && currentTarget.params.longitude !== undefined
        && currentTarget.params.latitude !== undefined
      ) {

        if (localStorage.getItem("position")) {
          let position = JSON.parse(localStorage.getItem("position"));
          if (currentTarget.params.longitude === null || currentTarget.params.longitude === "") {
            currentTarget.params.longitude = position.center.lng;
          }
          if (currentTarget.params.latitude === null || currentTarget.params.latitude === "") {
            currentTarget.params.latitude = position.center.lat;
          }
        }
        this.tagData.data.longitude = currentTarget.params.longitude;
        this.tagData.data.latitude = currentTarget.params.latitude;
        this.myGeo.lng = this.tagData.data.longitude;
        this.myGeo.lat = this.tagData.data.latitude;
      }
      const tempData = {
        label: this.tagData.data.label ? this.tagData.data.label : this.appGlobalService.defaultCityName, // 城市 页面不展示
        longitude: this.tagData.data.longitude, // 经度
        latitude: this.tagData.data.latitude,   // 纬度
        locationValue: this.tagData.data.latitude + ',' + this.tagData.data.longitude, // 坐标 页面不展示
        valueCssStyle: this.tagData.data.valueCssStyle // 地图的样式如高度
      };
      this.value = tempData;
    }


    if (this.value) {
      this.data = this.value;

      if (this.data.link && this.data.link.params && this.data.link.params.mapSearchType) {
        this.mapSearchType = this.data.link.params.mapSearchType;
        if (this.mapSearchType === 'community') {
          this.tagData = { data: { cityNameCssStyle: this.cityNameCssStyle, downArrowIconCssStyle: this.downArrowIconCssStyle } }
        }
        this.headerTitle = this.data.link.params.headerTitle;

      }
    }
    this.areaPositionInfo =
    {
      address: "",
      center: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).center : this.appGlobalService.defaultCityCenter,
      code: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).code : this.appGlobalService.defaultCityId,
      name: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).name : this.appGlobalService.defaultCityName,
      district: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).district : this.appGlobalService.defaultDistrictName,
      location: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).location : this.appGlobalService.defaultCityCenter
    };
    if (this.formData) {
      this.data = this.formData;
      this.data['cityName'] = this.formData.label;
      this.data['cityCode'] = this.formData.value;
      this.data['locationValue'] = this.formData.valueN;
    }
    this.mapId = 'mapId' + new Date().getTime();
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    const loading = await this.loadingCtrl.create({
      message: '',
      duration: 500
    });
    await loading.present();

    this.checkCurrentLocation(() => {
      this.clicked = false;
      if (!this.data.locationValue) {
        this.myGeo = { lng: this.myGeo.lng, lat: this.myGeo.lat };
        this.cityName = this.data.cityName;
      } else {
        const locationArr = this.data.locationValue.split(",");
        this.myGeo = { lng: Number(locationArr[1]), lat: Number(locationArr[0]) };
        this.cityName = this.data.cityName;
      }
      this.initMap(this.myGeo);

      if (this.mapSearchType === 'community') {
        // this.getCommunityAndRefreshList(this.myGeo);
        this.getDetailAddressBySearch(this.myGeo);
      } else {
        this.getDetailAddressAndRefreshList(this.myGeo);
      }

      loading.onDidDismiss();
    });

  }
  // tslint:disable-next-line:ban-types
  checkCurrentLocation(call: Function) {
    const that = this;
    that.platform.ready().then(() => {
      // 选择城市之后定位到指定城市名
      that.mapBaiduService.getPointByName(this.data.cityName, (point) => {
        const points = { lng: point.lng, lat: point.lat };
        that.myGeo.lat = points.lat;
        that.myGeo.lng = points.lng;
        call();
      });
    });
  }



  initMap(pt) {
    const that = this;
    const map = this.map = new BMap.Map(this.mapElement.nativeElement, { minZoom: 18, maxZoom: 18, enableMapClick: true });
    const pointCode = pt;
    map.disableKeyboard();
    map.disableDoubleClickZoom();
    map.disableScrollWheelZoom();
    map.disableContinuousZoom();


    let cust;
    if (this.appTypeCustom && this.appTypeCustom === 'LJ') {
      cust = new BMap.Icon("/assets/img/map/map_icon_location_yellow@3x.png", new BMap.Size(24, 34));
    } else {
      cust = new BMap.Icon("/assets/img/map/map_icon_location_red@3x.png", new BMap.Size(24, 34));
    }

    let gps;
    if (this.appTypeCustom && this.appTypeCustom === 'LJ') {
      gps = new BMap.Icon("/assets/img/map/map_icon_current_location.png", new BMap.Size(24, 34));
    } else {
      gps = new BMap.Icon("/assets/img/map/map_icon_location@3x.png", new BMap.Size(30, 30));
    }

    let point = new BMap.Point(pointCode.lng, pointCode.lat);
    let marker = new BMap.Marker(point, { icon: cust });
    let gpsMarker = new BMap.Marker(point, { icon: gps });

    function showLocationControl() { this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT; this.defaultOffset = new BMap.Size(10, 10); }

    showLocationControl.prototype = new BMap.Control();
    showLocationControl.prototype.initialize = () => {
      const div = document.createElement("div");
      div.style.width = "36px";
      div.style.height = "36px";
      div.style.boxShadow = "0px 0px 0px 0px rgba(39,40,46,0.1)";
      div.style.borderRadius = "5px";
      div.onclick = (e) => {
        that.platform.ready().then(() => {
          if (this.platform.is('cordova')) {
            cordova.plugins.baidumap_location.getCurrentPosition((res) => {
              console.log('res:' + res);
              // 国际转换坐标百度坐标
              res = that.mapBaiduService.storageNewLocation(res);
              const points = { lng: res.longitude, lat: res.latitude };
              that.myGeo.lng = points.lng;
              that.myGeo.lat = points.lat;
              point = new BMap.Point(that.myGeo.lng, that.myGeo.lat);
              marker = new BMap.Marker(point, { icon: gps });
              map.addOverlay(marker);
              map.centerAndZoom(new BMap.Point(that.myGeo.lng, that.myGeo.lat), 18);
              // that.getDetailAddressAndRefreshList(that.myGeo);
              that.gotoSearchCommunityOrDetailAddress(that.myGeo)
            },
              (err) => {
                if (err === 'show setting') {
                  console.log('show setting');
                  that.pageModalService.showSettingLocation();
                } else {
                  that.appGlobalService.showToast("请在设置中允许铺铺旺APP使用您的位置信息", 1000, "middle");
                }
                return;
              });
          } else {
            const myCity = new BMap.LocalCity();
            myCity.get((result) => {
              if (result !== undefined) {
                point = new BMap.Point(result.center.lng, result.center.lat);
                marker = new BMap.Marker(point, { icon: gps });
                gpsMarker = new BMap.Marker(point, { icon: gps });
                map.addOverlay(gpsMarker);
                map.centerAndZoom(new BMap.Point(result.center.lng, result.center.lat), 18);
                that.gotoSearchCommunityOrDetailAddress(point);
              }
            });
          }
        });
      };
      const lcbtn = document.createElement("img");
      lcbtn.style.width = "36px";
      lcbtn.style.height = "36px";
      lcbtn.src = "assets/img/map/map_icon_addr@3x.png";
      div.appendChild(lcbtn);
      map.getContainer().appendChild(div);
      return div;
    };
    const currlocationBtn = new showLocationControl();
    map.addControl(currlocationBtn);
    map.addOverlay(gpsMarker);
    map.centerAndZoom(point, 18);

    map.addEventListener('dragend', e => {
      map.removeOverlay(marker);
      const centerPt = map.getCenter();
      point = new BMap.Point(centerPt.lng, centerPt.lat);
      marker = new BMap.Marker(point, { icon: cust });
      map.addOverlay(marker);
      that.gotoSearchCommunityOrDetailAddress(point);
    });

    map.addEventListener("click", (e) => {
      map.removeOverlay(marker);
      point = new BMap.Point(e.point.lng, e.point.lat);
      marker = new BMap.Marker(point, { icon: cust });
      map.addOverlay(marker);
      that.gotoSearchCommunityOrDetailAddress(point);
    });

    map.addEventListener("tilesloaded", () => {
      const objs = document.getElementsByClassName(" anchorBL");
      if (objs !== undefined && objs.length > 0) {
        for (let i = 0, len = objs.length; i < len; i++) {
          if (objs[i] !== undefined) {
            objs[i].setAttribute("style", "display:none;");
          }
        }
      }
    });
  }

  gotoSearchCommunityOrDetailAddress(point) {
    let that = this;
    if (that.mapSearchType === 'community') {
      // that.getCommunityAndRefreshList(point);
      that.getDetailAddressBySearch(point);
    } else {
      that.getDetailAddressAndRefreshList(point);
    }
  }


  initMapAndSearch() {
    let that = this;
    setTimeout(() => {
      that.initMap(that.myGeo);
      // that.getDetailAddressAndRefreshList(that.myGeo);
      that.gotoSearchCommunityOrDetailAddress(that.myGeo);
    }, 100);
  }


  searchMap() {
    const that = this;
    if (this.streetDetail === '') {
      this.flag = true;
      this.initMapAndSearch();
      return;
    } else {
      this.flag = false;
      if (this.mapSearchType === 'community') {
        setTimeout(() => {
          that.gotoSearchCommunityOrDetailAddress(that.myGeo);
        }, 500);
      } else {
        let local = new BMap.LocalSearch(this.map);
        const pt = new BMap.Point(that.myGeo.lng, that.myGeo.lat); // 搜索中心点
        // if (this.mapSearchType === 'community') {
        //   local = new BMap.LocalSearch(that.map, pt,
        //     { renderOptions: { map: that.map } });
        // }
        local.setSearchCompleteCallback((searchResult) => {
          const s = [];
          if (searchResult && typeof (searchResult.getPoi) === 'function') {
            for (let i = 0; i < searchResult.getCurrentNumPois(); i++) {
              s.push(searchResult.getPoi(i));
            }
            that.searchList.data = s;
          }
        });
        // if (this.mapSearchType === 'community') {
        //   local.searchNearby(that.communityKey + ',' + this.streetDetail, pt, that.radius);
        // } else {
        local.search(this.data.cityName + this.streetDetail);
        // }
      }
    }
  }


  // 2.2.22 检索指定坐标附近的小区
  getCommunityAndRefreshList(point) {
    let that = this;
    const pt = new BMap.Point(point.lng, point.lat); // 搜索中心点
    const local = new BMap.LocalSearch(that.map, pt,
      { renderOptions: { map: that.map } });


    local.setSearchCompleteCallback((searchResult) => {
      console.log('经纬度小区搜索结果=：', searchResult);
      if (searchResult && typeof (searchResult.getPoi) === 'function') {
        const poi = searchResult.getPoi(0);
        if (poi) {
          setTimeout(() => {
            // that.initMap(poi.point);
            that.getDetailAddressAndRefreshList(poi.point);
          }, 50);
        }
      }
    });

    local.searchNearby(that.communityKey, pt, that.radius);
  }

  //2024.06.03 新增搜索接口
  getDetailAddressBySearch(point) {

    let cityCode = this.appGlobalService.defaultCityId;
    if (localStorage.getItem('currentCityPosition')) {
      cityCode = JSON.parse(localStorage.getItem('currentCityPosition')).code;
    } else if (localStorage.getItem('position')) {
      cityCode = JSON.parse(localStorage.getItem('position')).code;
    }


    let queryCondition1 = {
      sessionId: localStorage.getItem('sessionId'),
      pageId: this.appGlobalService.partnerApplySearchAreaPageId,
      params: {
        search: {
          base_info_base_name: this.streetDetail
        },
        latitude: point.lat,
        longitude: point.lng, cityCode, code: cityCode
      }
    };

    let queryCondition2 = {
      sessionId: localStorage.getItem('sessionId'),
      pageId: this.appGlobalService.partnerApplySearchAreaPageId,
      params: {
        latitude: point.lat,
        longitude: point.lng, cityCode, code: cityCode
      }
    };

    let queryCondition;
    if (this.streetDetail === undefined || this.streetDetail === '') {
      queryCondition = queryCondition2
    } else {
      queryCondition = queryCondition1;
    }


    this.http.post('application/page', queryCondition, res => {

      if (res) {
        // console.log(JSON.parse(res.script));
        if (JSON.parse(res.script) && JSON.parse(res.script).views[0]
          && JSON.parse(res.script).views[0].tags
        ) {
          const tempData = JSON.parse(res.script).views[0].tags;

          let dataListTag;
          for (let index = 0; index < tempData.length; index++) {
            const element = tempData[index];
            if (element.style === 'recommendChooseTag') {
              dataListTag = element;
              break;
            }
          }

          if (dataListTag && dataListTag.data && dataListTag.data.data) {
            let finalList = [];
            for (let index = 0; index < dataListTag.data.data.length; index++) {
              let singleTmp = {};
              const element = dataListTag.data.data[index];
              singleTmp['uid'] = element.uid;// uid
              singleTmp['title'] = element.title;// 小区名字
              singleTmp['address'] = element.address;// 详细地址
              singleTmp['value'] = element.title;
              singleTmp['cityCode'] = element.cityCode;// 城市ID
              singleTmp['districtCode'] = element.districtCode;// 区域ID
              singleTmp['location'] = element.location;// 经纬度
              singleTmp['city'] = element.city;// 城市
              finalList.push(singleTmp);
            }

            if (finalList.length > 0) {
              if (this.flag) {
                this.surroundingBusiness.data = finalList;
              } else {
                this.searchList.data = finalList;
              }

            }
          }

          // console.log(tagData);
        }
      }
    });


  }





  getDetailAddressAndRefreshList(point) {
    const that = this;
    const geoc = new BMap.Geocoder();
    const pt = new BMap.Point(point.lng, point.lat);
    geoc.getLocation(pt, rs => {
      that.surroundingBusiness.data = rs.surroundingPois;
      console.log('附近的点', that.surroundingBusiness.data);
      if (rs.surroundingPois && rs.surroundingPois.length > 0) {
        const item = rs.surroundingPois[0];
        item.district = rs.addressComponents.district;
        that.updateAddress.emit(item);
      }
    });








  }







  searchByStationName(city) {
    const that = this;
    const local = new BMap.LocalSearch(this.map, {
      renderOptions: { map: this.map }
    });
    local.setSearchCompleteCallback((searchResult) => {
      const poi = searchResult.getPoi(0);
      setTimeout(() => {
        that.initMap(poi.point);
        that.getDetailAddressAndRefreshList(poi.point);
      }, 100);
    });
    local.search(city);
  }
  touchClear(e) {
    const that = this;
    this.flag = true;
    that.streetDetail = '';
    setTimeout(() => {
      that.initMap(that.myGeo);
    }, 100);
  }
  async showCityModel() {
    const that = this;
    const modal = await this.modalController.create({
      component: ChooseCityComponent,
      componentProps: { modalTitle: '选择城市' }
    });
    modal.onDidDismiss().then((data) => {
      const value = data.data;
      that.cityName = value.n;
      that.cityCode = value.i;
      that.searchByStationName(that.cityName);
    });
    return await modal.present();
  }
  closeModel(item) {
    console.log(item, 'itmemememe');

    // const locationValue = item.point.lat.toString() + "," + item.point.lng.toString();
    // let districtId;
    // if (item.address) {
    //   const [result] = AddressParse.parse(item.address, true);
    //   console.log(result);
    //   districtId = result.code;
    // }

    const values = {
      cityName: item.city,
      value: item.title,
      location: item.location ? item.location : (item.point.lat.toString() + "," + item.point.lng.toString()),
      cityCode: this.areaPositionInfo.code,
      address: item.address,
      uid: item.uid,
      districtCode: item.districtCode,
    };

    if (item.address !== undefined) {
      this.modalController.dismiss(values);
    } else {
      this.modalController.dismiss();
    }
    if (document.getElementById('showSelectAddressModelId')) {
      document.getElementById('showSelectAddressModelId').removeAttribute('showAddressModal');
    }
  }
  dismiss() {
    this.modalController.dismiss(); if (document.getElementById('showSelectAddressModelId')) {
      document.getElementById('showSelectAddressModelId').removeAttribute('showAddressModal');
    }
  }
  goBack() {
    this.navController.navigateBack('address'); if (document.getElementById('showSelectAddressModelId')) {
      document.getElementById('showSelectAddressModelId').removeAttribute('showAddressModal');
    }
  }

  async chooseCity(target) {
    const that = this;
    const modal = await this.modalController.create({
      component: ChooseCityComponent,
      componentProps: { value: target, type: 0, modalTitle: '选择地址', changeCityPosition: 0 }
    });
    modal.onDidDismiss().then((res) => {

      if (res.data && res.data.center) {

        that.areaPositionInfo.center = res.data.center;
        that.areaPositionInfo.name = res.data.n;
        that.areaPositionInfo.code = res.data.i;

        this.checkCurrentLocation(() => {
          this.clicked = false;
          this.myGeo = { lng: that.areaPositionInfo.center.lng, lat: that.areaPositionInfo.center.lat };
          this.cityName = this.data.cityName;

          this.initMap(this.myGeo);
          this.getDetailAddressAndRefreshList(this.myGeo);

        });
      }
    });
    return await modal.present();
  }
}

